package virtualstock.stockgraph;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;


public class GetStockPrice 
{
	private static int stockID;
	private static Date date;
	private static double price;
	
	GetStockPrice(int stockID, Date date)
	{
		this.stockID = stockID;
		this.date = date;
		this.price = 0;
	}
	
	public static Connection getConnection(){
		try{
			Class.forName("com.mysql.jdbc.Driver");
			String url = "jdbc:mysql://localhost:3306/vstock";
			Connection conn = DriverManager.getConnection(url, "root", "xie");
			if(conn == null){
				System.out.println("null connection!");
			}
			return conn;
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}	
	}
	
	public static double getStockPrice()
	{

		
		Connection conn = GetStockPrice.getConnection();
		
		String sid = Integer.toString(stockID);
		String d = Integer.toString(date.getYear()) + "-" + Integer.toString(date.getMonth()) + "-" + Integer.toString(date.getDate());
		String sql = "SELECT current_price FROM price_history" 
			+ " WHERE price_history.stockID = " + sid + " AND price_history.date = " + "'" + d + "'";
		//System.out.println("sql is: " + sql);
		try
		{	
			Statement stmt = conn.createStatement();
			ResultSet rs;
			
			rs = stmt.executeQuery(sql);
			while(rs.next())
			{
				price = rs.getDouble("current_price");
				//System.out.println("price is: "+ price);
			}
		}
		catch(Exception e)
		{
			System.err.print("Error in database connection");
			e.printStackTrace();
		}
		
		return price;	
		
	}
	
}
